//
//  CouchFSController.m
//  CouchFS
//
//  Created by Tim Kofol on 1/24/08.
//  Copyright 2008 HighImpactNoise.com. All rights reserved.
//

#import "CouchFS.h"
#import "CouchFSController.h"
#import <MacFUSE/GMUserFileSystem.h>

@implementation CouchFSController
- (void)didMount:(NSNotification *)notification {
  NSDictionary* userInfo = [notification userInfo];
  NSString* mountPath = [userInfo objectForKey:@"mountPath"];
  NSString* parentPath = [mountPath stringByDeletingLastPathComponent];
  [[NSWorkspace sharedWorkspace] selectFile:mountPath
                   inFileViewerRootedAtPath:parentPath];
}

- (void)didUnmount:(NSNotification*)notification {
  [[NSApplication sharedApplication] terminate:nil];
}

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
  [self showConnect:self];
}

- (IBAction)showConnect:(id)sender {
  int connectResult = [NSApp runModalForWindow:connectPanel_];
  
  if (connectResult == NSRunAbortedResponse) {
    [connectPanel_ orderOut:self];
    return;
  }
  NSString *server   = [serverField_   stringValue];
  NSString *port     = [portField_   stringValue];

  [connectPanel_ orderOut:self];
  [self couchConnectWithServer:server Port:port];
}

- (IBAction)connectCancel:(id)sender {
  [NSApp abortModal];
}

- (IBAction)connectOK:(id)sender {
  [NSApp stopModal];
}

- (void)couchConnectWithServer:(NSString *)server Port:(NSString *)port{
  NSString *dbUrl =  [NSString stringWithFormat:@"http://%@:%@/", server, port];
  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center addObserver:self selector:@selector(didMount:)
                 name:kGMUserFileSystemDidMount object:nil];
  [center addObserver:self selector:@selector(didUnmount:)
                 name:kGMUserFileSystemDidUnmount object:nil];
  
  NSString* mountPath = [NSString stringWithFormat:@"/Volumes/CouchFS-%@", server];
  CouchFS* couchfs = [[CouchFS alloc] initWithRootDB:dbUrl];
  fs_ = [[GMUserFileSystem alloc] initWithDelegate:couchfs isThreadSafe:YES];
  NSMutableArray* options = [NSMutableArray array];
  NSString* volArg = 
  [NSString stringWithFormat:@"volicon=%@", 
   [[NSBundle mainBundle] pathForResource:@"Fuse" ofType:@"icns"]];
  [options addObject:volArg];  
  [options addObject:[NSString stringWithFormat:@"volname=CouchFS (%@)", server]];
  [fs_ mountAtPath:mountPath withOptions:options];
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  [fs_ unmount];  // Just in case we need to unmount;
  [[fs_ delegate] release];  // Clean up
  [fs_ release];
  return NSTerminateNow;
}

@end
